﻿using System;
using System.Linq;
using LogikBug.Collections;

namespace LogikBug.ModularMvc.Caching
{
	public class ModelCache : Hashtable<CacheKey<Type>, CacheKey<object>>
	{
		#region Fields



		#endregion

		#region Constructors



		#endregion

		#region Properties



		#endregion

		#region Methods

		public object GetValueOrDefault(Type key)
		{
			for (int i = 0; i < Keys.Count; i++)
			{
				if (Keys[i].CachedItem == key)
				{
					return Values[i].CachedItem;
				}
			}

			return null;
		}

		public T GetValueOrDefault<T>(Type key) where T : class
		{
			for (int i = 0; i < Keys.Count; i++)
			{
				if (Keys[i].CachedItem == key)
				{
					return Values[i].CachedItem as T;
				}
			}

			return null;
		}

		public bool Has(Type key)
		{
			return Keys.Any(t => t.CachedItem == key);
		}

		public void Add<TKey>(object value)
		{
			Add(typeof (TKey), value);
		}

		public void Add(Type key, object value)
		{
			if (Has(key))
			{
				var cacheKeyIndex = Keys.IndexOf(Keys.SingleOrDefault(k => k.CachedItem == key));
				ValuesList[cacheKeyIndex] = value;
				return;
			}

			Keyslist.Add(key);
			ValuesList.Add(value);
		}

		public TValue Get<TValue>()
		{
			return this[typeof(TValue)].CastAs<TValue>();
		}

		#endregion
	}
}
